package com.viu.technology.controller;

import com.github.pagehelper.PageInfo;
import com.viu.technology.dao.BaseDao;
import com.viu.technology.dto.PageBean;
import com.viu.technology.dto.Result;
import com.viu.technology.dto.ResultCode;
import com.viu.technology.po.Product;
import com.viu.technology.service.product.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @PostMapping("/entering")
    public Result<Product> enteringProduct(@RequestBody @Validated Product product, BindingResult bindingResult) {

        if (bindingResult.hasErrors()) {
            return Result.fail(ResultCode.DATA_CHECK_FAILURE, bindingResult.getFieldError().getDefaultMessage());
        }

        int result = productService.enteringProduct(product);

        if (result > 0) {
            return Result.success("录入成功");
        } else {
            return Result.fail(ResultCode.DATA_INSERT_FAILURE);
        }
    }


    @PostMapping("/all")
    public Result getAllProductWithPage(@RequestBody PageBean pageBean) {
        //BaseDao.setPageBean(pageBean.getCurrentPage(),pageBean.getPageSize() );
        PageInfo pageInfo = productService.getAllProductWithPage();
        return Result.success(pageInfo);
    }

    @GetMapping("/all/{currentPage}/{pageSize}")
    public Result getAllProduct2WithPage(@PathVariable int currentPage,@PathVariable int pageSize) {
        //BaseDao.setPageBean(pageBean.getCurrentPage(),pageBean.getPageSize() );
        PageInfo pageInfo = productService.getAllProductWithPage();
        return Result.success(pageInfo);
    }
}
